package ru.amse.tsyganov.jumleditor.editor;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.widgets.Canvas;

import ru.amse.tsyganov.jumleditor.commands.Command;
import ru.amse.tsyganov.jumleditor.commands.CommandFactory;
import ru.amse.tsyganov.jumleditor.commands.ViewsManager;
import ru.amse.tsyganov.jumleditor.model.ActivityGraph;
import ru.amse.tsyganov.jumleditor.model.State;
import ru.amse.tsyganov.jumleditor.view.ActivityGraphView;
import ru.amse.tsyganov.jumleditor.view.StateView;
import ru.amse.tsyganov.jumleditor.view.ViewElementFactory;

public class AddStateMode extends EditorMode {
	
	public static final AddStateMode instance = new AddStateMode();
	
	private final Cursor cursor;
	
	private ViewsManager viewsManager;
	private ActivityGraphView<ActivityGraph> activityGraphView;
	private Canvas canvas;
	
	private AddStateMode() {
		cursor = new Cursor(null, SWT.CURSOR_ARROW);
	}
	
	public void init(ViewsManager viewsManager, 
			ActivityGraphView<ActivityGraph> actionGraphView,
			Canvas canvas) {
		
		this.viewsManager = viewsManager;
		this.activityGraphView = actionGraphView;
		this.canvas = canvas;		
	}
	
	@Override
	public void setCursor() {
		canvas.setCursor(cursor);
	}

	@Override
	public void mouseDoubleClick(MouseEvent e) {
		checkState();
	}

	@Override
	public void mouseDown(MouseEvent e) {
		checkState();
		
		StateView<? extends State> newStateView = 
			ViewElementFactory.factory.createActionStateView();
		
		newStateView.setX(e.x);
		newStateView.setY(e.y);
		
		Command newStateCommand = 
			CommandFactory.createNewStateCommand(
					activityGraphView,
					newStateView);
		
		viewsManager.executeCommand(newStateCommand);
		
		canvas.redraw();
	}

	@Override
	public void mouseUp(MouseEvent e) {
		checkState();
	}

	private void checkState() {
		if (viewsManager == null || 
				activityGraphView == null) {
			
			throw new IllegalStateException();
		}
	}

	@Override
	public void paintControl(PaintEvent e) {
	}

	@Override
	public void mouseMove(MouseEvent e) {
	}

	@Override
	public void keyPressed(KeyEvent e) {
	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
}
